﻿Imports SIGI.Common.BE
Imports SIGI.Common.CommonDefinitions

Public Class UC_ABMOwner
#Region "<< -Attributes- >>"
    Private Const _UserName As String = "Nombre Propietario"
    Private Const _Dni As String = "Número Documento"
    Private Const _Cuit As String = "CUIT/L"

    Private _OwnerList As List(Of OwnerBE) = Nothing
    Private _FilterResultList As List(Of OwnerBE) = Nothing
    Private _SexList As List(Of SexBE) = Nothing
    Private _DocTypeList As List(Of DocumentTypeBE) = Nothing
    Private _CountryList As List(Of CountryBE) = Nothing
    Private _Properties As List(Of PropertyBE) = Nothing
#End Region

#Region "<< -Events- >>"
    Private Sub frmABMOwners_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim wSexController As SexController = Nothing
        Dim wCountryController As CountryController = Nothing
        Dim wDocTypeController As DocumentTypeController = Nothing
        Dim wCountry As CountryBE = Nothing

        Try
            If Me.DesignMode Then Return

            ReadOnlyControls(True)

            'Asigno los eventos
            AddHandler btnNew.Click, AddressOf btnNew_Click
            AddHandler btnUpdate.Click, AddressOf btnUpdate_Click
            AddHandler btnDelete.Click, AddressOf btnDelete_Click
            AddHandler btnSave.Click, AddressOf btnSave_Click
            AddHandler btnCancel.Click, AddressOf btnCancel_Click
            AddHandler txtDocNumber.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress
            AddHandler txtCuit.KeyPress, AddressOf GenericEvents.TextBoxCuit_KeyPress

            'Cargo el listado de Propietarios
            LoadOwners()

            'Cargo la lista de Sexos.
            GenericMethods.LoadSexListOnCombo(cmbSex, _SexList)

            'Cargo la lista de tipos de documentos.
            GenericMethods.LoadDocTypeListOnCombo(cmbDocType, _DocTypeList)

            'Cargo la lista de Países.
            wCountryController = New CountryController
            _CountryList = wCountryController.Search()
            wCountry = New CountryBE
            wCountry.Id = 0
            wCountry.Description = "Sin Selección"
            _CountryList.Insert(0, wCountry)
            cmbCountry.ValueMember = "Id"
            cmbCountry.DisplayMember = "Description"
            cmbCountry.DataSource = _CountryList
            cmbCountry.SelectedIndex = 0

            'Inicializo los filtros
            cmbFilterType.SelectedIndex = 0

        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
        Dim wOwnerController As OwnerController = Nothing
        Dim wOwner As OwnerBE = Nothing

        Try
            wOwnerController = New OwnerController
            wOwner = New OwnerBE
            wOwner.NotActive = chkNotActiveOwners.Checked

            If cmbFilterType.Text = _UserName Then
                wOwner.Name = txtFilter.Text.Trim
            ElseIf cmbFilterType.Text = _Dni Then
                wOwner.DocumentNumber = Convert.ToDecimal(txtFilter.Text.Trim)
            ElseIf cmbFilterType.Text = _Cuit Then
                wOwner.Cuit = txtFilter.Text.Trim
            End If

            _FilterResultList = wOwnerController.SearchByParams(wOwner)
            BindingSourceOwners.DataSource = _FilterResultList

            txtFilter.Text = String.Empty
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbFilterType_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbFilterType.SelectedIndexChanged
        Try
            If cmbFilterType.Text = _Dni Then
                AddHandler txtFilter.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress
            Else
                RemoveHandler txtFilter.KeyPress, AddressOf GenericEvents.TextBoxNumeric_KeyPress
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnNew_Click(sender As System.Object, e As System.EventArgs)
        Try
            If Not _Properties Is Nothing Then _Properties.Clear()
            ButtonController(btnNew.Name)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs)
        Dim wOwner As OwnerBE = Nothing
        Try
            If GridView1.RowCount = 0 Then Return

            ButtonController(btnUpdate.Name)
            wOwner = _OwnerList(GridView1.FocusedRowHandle)
            'Sexo
            cmbSex.SelectedValue = wOwner.Sex.Id
            'Pais
            cmbCountry.SelectedValue = wOwner.Country.Id
            'Ciudad
            cmbCity.SelectedValue = wOwner.City.Id
            'Provincia
            cmbProvince.SelectedValue = wOwner.Province.Id
            'Tipo Doc.
            cmbDocType.SelectedValue = wOwner.DocumentType.Id
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs)
        Dim wMotive As String = String.Empty
        Dim wInputBox As frmInputVisorBox = Nothing
        Dim wOwner As OwnerBE = Nothing
        Dim wOwnerController As OwnerController = Nothing

        Try
            If GridView1.RowCount = 0 Then Return

            If _MsgBox.ShowMessage("ABM Propietarios", "¿Está Seguro de dar de baja al Propietario?",
                              frmMessage.MessageType.Question_,
                              frmMessage.MessageButtons.OkCancel) = frmMessage.MsgResult.Cancel Then
                Return
            End If
            wInputBox = New frmInputVisorBox
            wMotive = wInputBox.ShowBox("Baja de Propietario", frmInputVisorBox.Behavior.Write, "Cese de Servicio")

            wOwner = _OwnerList(GridView1.FocusedRowHandle)
            wOwner.EndDate = Date.Today
            wOwner.AccountCloseMotive = wMotive
            wOwner.NotActive = True

            wOwnerController = New OwnerController
            If (Not wOwnerController.Delete(wOwner)) Then
                _MsgBox.ShowMessage("Baja de Propietario", "El Propietario no pudo darse de baja ya que posee propiedades con contratos aun no vencidos",
                                    frmMessage.MessageType.Information_,
                                    frmMessage.MessageButtons.Ok)
            End If

            LoadOwners(Not chkNotActiveOwners.Checked)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs)
        Try
            If InsertUpdateOwner() Then
                If _Behavior = Common.CommonDefinitions.CRUD.Insert Then
                    _MsgBox.ShowMessage("ABM Propietarios", "Propietario Guardado con Éxito", frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
                ElseIf _Behavior = Common.CommonDefinitions.CRUD.Update Then
                    _MsgBox.ShowMessage("ABM Propietarios", "Propietario Actualizado con Éxito", frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
                End If
                ButtonController(btnSave.Name)
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs)
        ButtonController(btnCancel.Name)
    End Sub

    Private Sub btnRemoveFilter_Click(sender As System.Object, e As System.EventArgs) Handles btnRemoveFilter.Click
        LoadOwners(Not chkNotActiveOwners.Checked)
    End Sub

    Private Sub GridView1_RowCellClick(sender As System.Object, e As DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs) Handles GridView1.RowCellClick
        Dim wRowIdx As Integer = 0
        Dim wOwner As OwnerBE = Nothing

        Try
            wRowIdx = e.RowHandle
            wOwner = _OwnerList(wRowIdx)
            LoadOwnerData(wOwner)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbCountry_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbCountry.SelectedValueChanged
        Dim wCountryId As Integer = 0

        Try
            wCountryId = Convert.ToInt32(cmbCountry.SelectedValue)
            GenericMethods.GetProvinceByCountryId(wCountryId, cmbProvince)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub cmbProvince_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cmbProvince.SelectedValueChanged
        Dim wProvinceId As Integer = 0

        Try
            wProvinceId = Convert.ToInt32(cmbProvince.SelectedValue)
            GenericMethods.GetCityByProvinceId(wProvinceId, cmbCity)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub chkNotActiveOwners_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkNotActiveOwners.CheckedChanged
        Try
            LoadOwners(Not chkNotActiveOwners.Checked)
            btnDelete.Enabled = Not chkNotActiveOwners.Checked
            gridOwners.ContextMenuStrip = IIf(chkNotActiveOwners.Checked, ContextMenuInactiveOwners, Nothing)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub VerMotivoDeBajaToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles VerMotivoDeBajaToolStripMenuItem.Click
        Dim wInputBox As frmInputVisorBox = Nothing
        Dim wOwner As OwnerBE = Nothing

        Try
            If GridView1.RowCount = 0 Then Return

            wOwner = _OwnerList(GridView1.FocusedRowHandle)
            wInputBox = New frmInputVisorBox
            wInputBox.ShowBox("Motivo de Baja de Propietario", frmInputVisorBox.Behavior.Read, wOwner.AccountCloseMotive)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub ReactivarPropietarioToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ReactivarPropietarioToolStripMenuItem.Click
        Dim wOwner As OwnerBE = Nothing
        Dim wOwnwerController As OwnerController = Nothing

        Try
            If GridView1.RowCount = 0 Then Return

            wOwner = _OwnerList(GridView1.FocusedRowHandle)
            wOwner.EndDate = Nothing
            wOwner.AccountCloseMotive = String.Empty
            wOwner.NotActive = False

            wOwnwerController = New OwnerController
            wOwnwerController.Update(wOwner)

            LoadOwners(Not chkNotActiveOwners.Checked)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnAddProperty_Click(sender As System.Object, e As System.EventArgs) Handles btnAddProperty.Click
        Dim wFrmNewProperties As frmNewProperty = Nothing

        Try
            wFrmNewProperties = New frmNewProperty(False, _Properties) With {.Behavior = CRUD.Insert}
            wFrmNewProperties.ShowDialog()
            _Properties = wFrmNewProperties.Properties
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub
#End Region

#Region "<< -Methods- >>"
    Private Sub LoadOwners(Optional pActive As Boolean = True)
        Dim wOwnerController As OwnerController = New OwnerController

        _OwnerList = wOwnerController.Search(pActive)
        BindingSourceOwners.DataSource = _OwnerList
    End Sub

    Private Sub ButtonController(pButton As String)
        Select Case pButton
            Case btnNew.Name
                ReadOnlyControls(False, True)

                btnCancel.Enabled = True
                btnSave.Enabled = True
                btnDelete.Enabled = False
                btnNew.Enabled = False
                btnUpdate.Enabled = False

                txtDocType.Visible = False
                cmbDocType.Visible = True
                txtCountry.Visible = False
                cmbCountry.Visible = True
                txtProvince.Visible = False
                cmbProvince.Visible = True
                txtCity.Visible = False
                cmbCity.Visible = True
                txtSex.Visible = False
                cmbSex.Visible = True

                btnSearch.Enabled = False
                btnRemoveFilter.Enabled = False

                chkNotActiveOwners.Enabled = False

                If cmbSex.Text.ToLower = "femenino" Then
                    txtCuit.Text = "27-"
                ElseIf cmbSex.Text.ToLower = "masculino" Then
                    txtCuit.Text = "20-"
                End If
                btnAddProperty.Enabled = True

                _Behavior = Common.CommonDefinitions.CRUD.Insert

            Case btnUpdate.Name
                ReadOnlyControls(False)

                btnCancel.Enabled = True
                btnSave.Enabled = True
                btnDelete.Enabled = False
                btnNew.Enabled = False
                btnUpdate.Enabled = False

                txtDocType.Visible = False
                cmbDocType.Visible = True
                txtCountry.Visible = False
                cmbCountry.Visible = True
                txtProvince.Visible = False
                cmbProvince.Visible = True
                txtCity.Visible = False
                cmbCity.Visible = True
                txtSex.Visible = False
                cmbSex.Visible = True

                btnSearch.Enabled = False
                btnRemoveFilter.Enabled = False

                chkNotActiveOwners.Enabled = False
                _Behavior = Common.CommonDefinitions.CRUD.Update

            Case btnDelete.Name
                ReadOnlyControls(True, True)

                _Behavior = Common.CommonDefinitions.CRUD.Delete

            Case btnSave.Name
                ReadOnlyControls(True, True)

                btnCancel.Enabled = False
                btnSave.Enabled = False
                btnNew.Enabled = True
                btnDelete.Enabled = True
                btnUpdate.Enabled = True

                txtDocType.Visible = True
                cmbDocType.Visible = False
                txtCountry.Visible = True
                cmbCountry.Visible = False
                txtProvince.Visible = True
                cmbProvince.Visible = False
                txtCity.Visible = True
                cmbCity.Visible = False
                txtSex.Visible = True
                cmbSex.Visible = False

                btnSearch.Enabled = True
                btnRemoveFilter.Enabled = True

                chkNotActiveOwners.Enabled = True
                btnAddProperty.Enabled = False

                _Behavior = Common.CommonDefinitions.CRUD.Read

            Case btnCancel.Name
                ReadOnlyControls(True, True)

                btnCancel.Enabled = False
                btnSave.Enabled = False
                btnNew.Enabled = True
                btnDelete.Enabled = True
                btnUpdate.Enabled = True

                txtDocType.Visible = True
                cmbDocType.Visible = False
                txtCountry.Visible = True
                cmbCountry.Visible = False
                txtProvince.Visible = True
                cmbProvince.Visible = False
                txtCity.Visible = True
                cmbCity.Visible = False
                txtSex.Visible = True
                cmbSex.Visible = False

                btnSearch.Enabled = True
                btnRemoveFilter.Enabled = True

                chkNotActiveOwners.Enabled = True
                btnAddProperty.Enabled = False

                _Behavior = Common.CommonDefinitions.CRUD.Read

            Case Else

        End Select
    End Sub

    Private Function InsertUpdateOwner() As Boolean
        Dim wOwner As OwnerBE = Nothing
        Dim wOwnerController As OwnerController = Nothing

        Try
            If Not ValidateRequiredFields() Then Return False

            wOwner = New OwnerBE
            wOwner.Name = txtName.Text.Trim
            wOwner.DocumentType = New DocumentTypeBE
            wOwner.DocumentType.Id = cmbDocType.SelectedValue
            wOwner.DocumentNumber = txtDocNumber.Text.Trim
            wOwner.Sex = New SexBE
            wOwner.Sex.Id = cmbSex.SelectedValue
            wOwner.Cuit = txtCuit.Text.Trim
            wOwner.Country = New CountryBE
            wOwner.Country.Id = cmbCountry.SelectedValue
            wOwner.Province = New ProvinceBE
            wOwner.Province.Id = cmbProvince.SelectedValue
            wOwner.City = New CityBE
            wOwner.City.Id = cmbCity.SelectedValue
            wOwner.Direction = txtDirection.Text.Trim
            wOwner.PostalCode = txtPostalCode.Text.Trim
            wOwner.Phone = txtPhone.Text.Trim
            wOwner.AuxiliarPhone = txtAuxPhone.Text.Trim
            wOwner.Email = txtEmail.Text.Trim
            wOwner.Properties = _Properties

            'Intento insertar el propietario
            wOwnerController = New OwnerController
            If _Behavior = Common.CommonDefinitions.CRUD.Insert Then
                wOwnerController.Insert(wOwner)
            ElseIf _Behavior = Common.CommonDefinitions.CRUD.Update Then
                wOwner.Id = _OwnerList(GridView1.FocusedRowHandle).Id
                wOwnerController.Update(wOwner)
            End If

            LoadOwners(Not chkNotActiveOwners.Checked)
        Catch ex As Exception
            Return False
        End Try

        Return True
    End Function

    Private Function ValidateRequiredFields() As Boolean
        If String.IsNullOrEmpty(txtName.Text.Trim) Then
            txtName.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtDocNumber.Text.Trim) Then
            txtDocNumber.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtCuit.Text.Trim) Then
            txtCuit.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtPhone.Text.Trim) Then
            txtPhone.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtPostalCode.Text.Trim) Then
            txtPostalCode.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If String.IsNullOrEmpty(txtDirection.Text.Trim) Then
            txtDirection.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If cmbCountry.SelectedValue = 0 Then 'Sin Selección
            cmbCountry.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If cmbProvince.SelectedValue = 0 Then
            cmbProvince.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If
        If cmbCity.SelectedValue = 0 Then
            cmbCity.Focus()
            _MsgBox.ShowMessage("ABM Propietarios", "Faltan datos Obligatorios", frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
            Return False
        End If

        Return True
    End Function

    Private Sub ReadOnlyControls(pReadOnly As Boolean, Optional pCleanCtrl As Boolean = False)
        For Each wCtrl As Control In grpOwnerData.Controls
            If TypeOf wCtrl Is TextBox Then
                DirectCast(wCtrl, TextBox).ReadOnly = pReadOnly
                If pCleanCtrl Then DirectCast(wCtrl, TextBox).Text = String.Empty
            End If
            If TypeOf wCtrl Is ComboBox Then DirectCast(wCtrl, ComboBox).Enabled = Not pReadOnly
        Next
    End Sub

    Private Sub LoadOwnerData(pOwner As OwnerBE)
        Dim wProvinceList As List(Of ProvinceBE) = Nothing
        Dim wCityList As List(Of CityBE) = Nothing

        If _Behavior <> CRUD.Read Then Return

        ReadOnlyControls(True)

        With pOwner
            txtName.Text = .Name
            txtDocType.Text = .DocumentType.Description
            txtDocNumber.Text = .DocumentNumber
            txtSex.Text = .Sex.Description
            txtCuit.Text = .Cuit
            txtDirection.Text = .Direction
            If Not .Country Is Nothing Then
                txtCountry.Text = .Country.Description
            End If
            If Not .Province Is Nothing Then
                txtProvince.Text = .Province.Description
            End If
            If Not .City Is Nothing Then
                txtCity.Text = .City.Description
            End If
            txtPostalCode.Text = .PostalCode
            txtPhone.Text = .Phone
            txtAuxPhone.Text = .AuxiliarPhone
            txtEmail.Text = .Email
        End With
    End Sub

#End Region
End Class
